package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import cn.com.kh.LogToDB
import cn.com.kh.signUtil
import com.alibaba.fastjson.JSONArray
import net.sf.json.JSONObject
import com.alibaba.fastjson.parser.Feature
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.bouncycastle.util.encoders.Base64Encoder
import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource
import sun.misc.BASE64Decoder
import sun.misc.BASE64Encoder

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.lang.reflect.Array
import java.text.SimpleDateFormat

/**
 * 客户-个人/企业认证
 */

public class apiFDDAuthentication implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiFDDAuthentication.class);
    private static String APPKEY = "QwM7K28TpIk6USVFq9NfHDcW";
    private static String APPID;
    private static String URL;
    private String charset = "utf-8"; //设置字符集
    private int timeout = 100000; //设置请求超时时间
    private int enableSSLflag = 0;
    private String LOCALURL = "";
    private String CALLBACKURL = "";

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        long startTime = System.currentTimeMillis();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        // 初始化返回参数
        JSONObject result = new JSONObject();
        String v_interfacetype = request.getParameter("interfacetype");

        JSONObject resultJson = null;
        //接收客户端调用参数
        String callJson = "";
        InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
        BufferedReader iny = new BufferedReader(reader);
        String line;
        while ((line = iny.readLine()) != null) {
            callJson += line;
        }

        log.info("[调用请求信息]：" + callJson);
        try {
            JSONObject inJson = JSONObject.fromObject(callJson);

            LOCALURL = KHDBConfig.getAPIURL(eliteBean, "Groovy-Inner");
            URL = KHDBConfig.getAPIURL(eliteBean, "fddurl");
            CALLBACKURL = KHDBConfig.getAPIURL(eliteBean, "callbackip");
            APPKEY = KHDBConfig.getParam(eliteBean, "FDDKEY");
            APPID = KHDBConfig.getParam(eliteBean, "FDDID");

            String customerTypeSql = "Select CUSTOMERTYPE From customer Where FDD_CUSTOMERID = '"+ inJson.getString("customerId")+"'";
            List customerTypeList = eliteBean.chaxun_sql(customerTypeSql,"dataSource");

            String customerType = customerTypeList.get(0).getAt("CUSTOMERTYPE");
            log.info("[客户类型]：" + customerType);

            if (customerType == "个人") {
                result = personAuth(inJson);
            }else if(customerType == "公司"){
                result = personcompanyAuth(inJson);
            } else {
                result.put("code", 1009);
                result.put("msg", "未知客户类型："+customerType);
            }

        } catch (Exception e) {
            result.put("code", 1008);
            result.put("msg", e.getMessage());
        } finally {
            LogToDB.toDB(eliteBean, "dataSource", "内部调用FDD认证转发", "apiFDDAuthentication", callJson, result.toString(), (System.currentTimeMillis() - startTime).toString(), v_interfacetype);
        }
        return result.toString();
    }

    //个人认证
    public JSONObject personAuth(JSONObject inJson) {
        HashMap<String, Object> headMap = new HashMap<>();
        headMap.put("Content-Type", "application/json");
        inJson.put("verifiedWay", 9);
        inJson.put("pageModify", 2);
        inJson.put("isSendSms", 1);
        inJson.put("isRepeatVerified", 1);
        inJson.put("notifyUrl", CALLBACKURL + "/api/apiCustomerCallback");
        String bizContent = getbizContent(inJson.toString());
        bizContent = bizContent.replaceAll("\\n", "").replaceAll("\\r", ""); ;
        JSONObject jsons = new JSONObject();
        String datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        jsons.put("timestamp", datetime);
        jsons.put("bizContent", bizContent);
        jsons.put("signType", "SHA256");
        jsons.put("appId", APPID);
        String signString = "appId=" + APPID + "&bizContent=" + bizContent + "&signType=SHA256&timestamp=" + datetime;
        signString = signString.replace("\\n", "");

        String signstr1 = Util.getSHA256Str(signString).toUpperCase();
        String signstr2 = Util.getSHA256Str(signstr1 + APPKEY).toUpperCase();
        String sign = new BASE64Encoder().encodeBuffer(signstr2.getBytes("UTF-8"));
        jsons.put("sign", sign);

        log.debug("用户个人认证参数:" + jsons.toString().replace("\\n", ""));
        String Assemblys = Util.doHttpPostUseHead(URL + "/certification/person/url", jsons.toString().replace("\\n", ""), charset, timeout, enableSSLflag, headMap);

        JSONObject obj = JSONObject.fromObject(Assemblys);
        return obj;
    }

    //企业认证
    public JSONObject personcompanyAuth(JSONObject inJson) {

        HashMap<String, Object> headMap = new HashMap<>();
        headMap.put("Content-Type", "application/json");
        inJson.put("verifiedWay", 0);
        inJson.put("pageModify", 2);
        inJson.put("isSendSms", 1);
        inJson.put("isRepeatVerified", 2);//1-首次认证，2-重新认证
        inJson.put("companyPrincipalType", 2);
        inJson.put("notifyUrl", CALLBACKURL + "/api/apiCustomerCallback");
        JSONObject AgentInfoDTO = new JSONObject();
        AgentInfoDTO.put("agentMobile", inJson.getString("mobile"));
        inJson.put("agentInfo",AgentInfoDTO);
        String bizContent = getbizContent(inJson.toString());
        bizContent = bizContent.replaceAll("\\n", "").replaceAll("\\r", ""); ;
        JSONObject jsons = new JSONObject();
        String datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        jsons.put("timestamp", datetime);
        jsons.put("bizContent", bizContent);
        jsons.put("signType", "SHA256");
        jsons.put("appId", APPID);
        String signString = "appId=" + APPID + "&bizContent=" + bizContent + "&signType=SHA256&timestamp=" + datetime;
        signString = signString.replace("\\n", "");

        String signstr1 = Util.getSHA256Str(signString).toUpperCase();
        String signstr2 = Util.getSHA256Str(signstr1 + APPKEY).toUpperCase();
        String sign = new BASE64Encoder().encodeBuffer(signstr2.getBytes("UTF-8"));
        jsons.put("sign", sign);

        log.debug("用户公司认证参数:" + jsons.toString().replace("\\n", ""));
        String Assemblys = Util.doHttpPostUseHead(URL + "/certification/company/url", jsons.toString().replace("\\n", ""), charset, timeout, enableSSLflag, headMap);

        JSONObject obj = JSONObject.fromObject(Assemblys);
        return obj;
    }

    //获取bizContent
    public String getbizContent(String param) {
        log.debug("param:" + param);
        String encodedObject = URLEncoder.encode(param, "UTF-8");
        String biz_contents = new BASE64Encoder().encodeBuffer(encodedObject.getBytes("UTF-8"));
        log.info("[biz_contents]:" + biz_contents);
        return biz_contents;
    }
}